package com.dily.study.demo.config.websocket.first;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Date: 2022-04-28 星期四
 * Time: 14:43
 * Author: Dily_Su
 * Remark:
 * websocket 消息处理类，类似于controller
 */
@Component
public class DefaultHandler implements WebSocketHandler {

    Map<String, WebSocketSession> conns = new HashMap<>();

    /**
     * 建立连接
     *
     * @param session 会话
     * @throws Exception 异常
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 缓存用户信息: userInfo
        session.getLocalAddress(); // 获取本地IP
        session.getUri();
        session.getAttributes();
        session.getPrincipal();
        session.getAcceptedProtocol();
        session.getId();
        conns.put(session.getId(), session);
    }

    /**
     * 接收消息
     *
     * @param session 会话
     * @param message 消息
     * @throws Exception 异常
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // 接收消息
        conns.forEach((k, v) -> {
            try {
                v.sendMessage(new TextMessage(session.getId() + "说:" + message.getPayload().toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 发生错误
     *
     * @param session   会话
     * @param throwable throwable
     * @throws Exception 异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
        // 清除用户缓存信息
    }

    /**
     * 关闭连接
     *
     * @param session     会话
     * @param closeStatus 关闭状态
     * @throws Exception 异常
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // 清除用户缓存信息
    }

    /**
     * 是否支持发送部分消息
     *
     * @return true/false
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 自定义发送消息
     *
     * @param message  消息
     * @param username 用户名
     */
    public void sendMessage(String message, String username) {
    }
}
